<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Exportw extends CI_Controller {

	var $debug = '';
	var $per_page = '';

	public function __construct()
	{
		parent::__construct();	

		$logged_in = $this->session->userdata('logged_in');
		if($logged_in)
		{
		   $session_data = $this->session->userdata('logged_in');
		   $data['username'] = $session_data['username'];		   
		}
		else
		{
	     //If no session, redirect to login page
	     redirect('login', 'refresh');
   		}

   		/////////////////// Previleage section ///////////////////////////////////
   		//retrieve information
   		// load model
   		$this->load->model('User_model');
   		$userInfo = $this->User_model->userInfo($data['username']);   		

   		if(empty($userInfo))
   		{
   			redirect('login', 'refresh');
   		}
   		else
   		{
   			// check previleage
   			$this->is_edit = $userInfo->is_edit;
   			$this->is_view = $userInfo->is_view;   			
   		}   		

   		// get controller request
   		$controller_call = $this->uri->segment(1);
   		$action_call = $this->uri->segment(2);

   		$full_call = $controller_call . '/' . $action_call;

   		$list_view_pages = array('exportw/history');
   		$list_edit_pages = array('exportw/index');

   		if(in_array($full_call, $list_view_pages))
   		{
   			if(!$this->is_view)
   				redirect('privileage/error');
   		}
   		else if(in_array($full_call, $list_edit_pages))
   		{
   			if(!$this->is_edit)
   				redirect('privileage/error');
   		}
   		else if($controller_call == 'exportw')	// special action
   		{
   			if(!$this->is_edit)
   				redirect('privileage/error');
   		}
   		////////////////////////////////////////////////////////////////////////////

		// gán giá trị tiêu đề form
		$this->template->set('nav',$this->uri->segment(1));
		$this->template->set('title', 'Xuất kho');
		$this->template->set('section', 'Xuất kho');			

		// load model kho
		$this->load->model('Storage_model');	
		// load model history kho
		$this->load->model('Storage_product_history_model');
		// load products that in storage
		$this->load->model('Storage_product_model');
		// load product size
		$this->load->model('Product_sizes_model');
		// load product model
		$this->load->model('Product_model');
		// load model code_export_form
		$this->load->model('Code_export_form_model');
		// load model export temporary
		$this->load->model('Code_export_form_tmp_model');
		// 
		$this->load->model('Export_form_model');		

		// enable debug
		$this->debug = array();

		// init per page
		$this->per_page = 20;	// limit per page is 20		
	}

	// index 
	// list all storage with empty space available
	public function index($export_p = false)
	{			
		// load inactive export then ask to finish first
		$exportForm = $this->Export_form_model->getInactiveExportForm();
		
		// get warning data
		$warning = $this->session->userdata('warning');

		$data['success'] = $this->session->userdata('notify');
		$this->session->unset_userdata('notify');

		$this->load->library('pagination');				

		// limit per page export products		
		if(empty($export_p))
			$export_p = 1;		

		if(!empty($exportForm))
		{
			// deactive button create new export
			$data['inactiveMakeExport'] = 'yes';
		
			// condition
			$query_condition = array(
					'code_export_form'	=> $exportForm->id,					
				);

			// list all code will output
			$return = $this->Code_export_form_model->loadAllV2($query_condition);						

			$data['exportCodes'] = $return['return'];			

			$tmp_export_codes = array();

			foreach ($data['exportCodes'] as $code) 
			{
				$product_size = $this->Product_sizes_model->getEntry('code', $code->code);
				$product = $this->Product_model->getEntry($product_size->product_id);

				$tmp_export_codes[] = array(
						'id'			=>	$code->id,				
						'product_name'	=>	$product->title,
						'color'			=>	$product->color,
						'product'		=>	$product,
						'product_size'	=>	$product_size->size,
						'storage'		=>	$code->storage,
						'product_code'	=>	$code->code,
						'date_created'	=>	$code->date_created,							
					);
			}			

			$data['exportCodes'] = $tmp_export_codes;			

			// 
			$data['notify'] = "Có 1 phiếu xuất kho đang chờ xử lý !";
		}
		else
		{
			$data['noitfy'] = "Xin vui lòng bấm nút tạo phiếu xuất kho trước khi xuất hàng";
		}

		// limit and start 
		$limit_spm = $this->per_page;
		$start_spm = ($export_p - 1) * $this->per_page;

		// get all records in storage product
		$return = $this->Storage_product_model->loadAllV2($limit_spm, $start_spm);

		$data['storageProducts'] = $return['data'];
		$total_storage_products = $return['count'];
		// luu data
		$data['total'] = $total_storage_products;

		////////////////// pagination //////////////////////////////////////
		$config['base_url'] = site_url('exportw/index/');
		$config['total_rows'] = $total_storage_products;
		$config['per_page'] = $this->per_page;
		$config['uri_segment'] = 3;
		$config['use_page_numbers'] = TRUE;
		$config['full_tag_open'] = '<ul class="pagination">';
		$config['full_tag_close'] = '</ul>';
		// first link
		$config['first_link'] = '&laquo;';
		$config['first_tag_open'] = '<li>';
		$config['first_tag_close'] = '</li>';
		// next link
		$config['next_tag_open'] = '<li>';
		$config['next_tag_close'] = '</li>';	
		// previous link
		$config['prev_tag_open'] = '<li>';
		$config['prev_tag_close'] = '</li>';
		// end link
		$config['last_link'] = '&raquo;';
		$config['last_tag_open'] = '<li>';
		$config['last_tag_close'] = '</li>';
		// current
		$config['cur_tag_open'] = '<li class="active"><a href="#">';
		$config['cur_tag_close'] = '<span class="sr-only">(current)</span></a></li>';
		// digit link
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';

		$this->pagination->initialize($config); 

		$data['paging_exportproducts'] = $this->pagination->create_links();

		////////////////////////////////////////////////////////////////////
		
		if(!isset($data['storageProducts']) && empty($data['storageProducts']) && count($data['storageProducts']) > 0)
		{
			$data['notify'] = 'Chưa có sản phẩm nào lưu kho';
		}
		else
		{
			$tmp_storageProds = array();		
			foreach ($data['storageProducts'] as $row) 
			{
				$productObj = $this->Product_model->getEntry($row->product_id);			

				$tmp_storageProds[] = array(
						'id'			=>	$row->id,				
						'product_name'	=>	$productObj->title,
						'color'			=>	$productObj->color,
						'product'		=>	$this->Product_model->getEntry($row->product_id),
						'product_size'	=>	$this->Product_sizes_model->getEntry('code', $row->product_code),
						'storage'		=>	$this->Storage_model->getEntry($row->storage_id),
						'product_code'	=>	$row->product_code,
						'date_created'	=>	$row->created_date,
					);
			}

			$data['storageProducts'] = $tmp_storageProds;
		}		

		$data['storageProducts'] = $tmp_storageProds;

		$this->session->set_userdata('currentURL', current_url());

		$this->template->load('admin/template','admin/exportw',$data);
	}

	// tìm kiếm
	public function search($search_index = false, $export_p = false)
	{
		$search = $this->input->post('search');		
		$size = $this->input->post('size');		

		$data['search'] = '';
		if(!empty($search))
		{
			$data['search'] = $search;
			$this->session->set_userdata('search',$data['search']);
		}
		else if(!empty($search_index))
		{
			$data['search'] = $search_index;
		}				

		if(!empty($size))
		{
			$data['size'] = $size;
			$this->session->set_userdata('size',$data['size']);
		}

		$session_size = $this->session->set_userdata('size');

		if(!empty($session_size))
		{
			$data['size'] = $session_size;
		}
		
		$search_index_uri = '';
		if(!empty($data['search']))
		{
			$search_index_uri = $data['search'];			
		}
		else
		{
			$search_index_uri = 'false';
			$this->session->unset_userdata('search');
		}

		$session_search = $this->session->userdata('search');

		if(!empty($session_search))
		{
			$data['search'] = $session_search;			
		}

		// limit per page export products		
		if(empty($export_p))
			$export_p = 1;
		
		// load inactive export then ask to finish first
		$exportForm = $this->Export_form_model->getInactiveExportForm();
		
		// get warning data
		$warning = $this->session->userdata('warning');

		$data['success'] = $this->session->userdata('notify');
		$this->session->unset_userdata('notify');
				
		// load library pagination
		$this->load->library('pagination');

		if(!empty($exportForm))
		{
			// deactive button create new export
			$data['inactiveMakeExport'] = 'yes';

			// list all code will output
			$data['exportCodes'] = $this->Code_export_form_model->loadAll($exportForm->id);

			$tmp_export_codes = array();

			foreach ($data['exportCodes'] as $code) 
			{
				$product_size = $this->Product_sizes_model->getEntry('code', $code->code);
				$product = $this->Product_model->getEntry($product_size->product_id);

				$tmp_export_codes[] = array(
						'id'			=>	$code->id,				
						'product_name'	=>	$product->title,
						'color'			=>	$product->color,
						'product'		=>	$product,
						'product_size'	=>	$product_size->size,
						'storage'		=>	$code->storage,
						'product_code'	=>	$code->code,
						'date_created'	=>	$code->date_created,							
					);
			}			

			$data['exportCodes'] = $tmp_export_codes;

			// 
			$data['notify'] = "Có 1 phiếu xuất kho đang chờ xử lý !";
		}
		else
		{
			$data['noitfy'] = "Xin vui lòng bấm nút tạo phiếu xuất kho trước khi xuất hàng";
		}

		$cond['product_code'] = $this->accents->removeaccents($data['search']);
		$cond['product_code'] = url_title($cond['product_code']);

		if(!empty($data['size']))
			$cond['size'] = $data['size'];

		// limit and start 
		$limit_spm = $this->per_page;
		$start_spm = ($export_p - 1) * $this->per_page;

		// get all records in storage product
		$return = $this->Storage_product_model->loadAllV3($limit_spm, $start_spm, $cond);

		$data['storageProducts'] =  $return['data'];
		$total_storage_products = $return['count'];		
		$data['total'] = $total_storage_products;

		////////////////// pagination //////////////////////////////////////
		$config['base_url'] = site_url('exportw/search/'.$search_index_uri.'/');
		$config['total_rows'] = $total_storage_products;
		$config['per_page'] = $this->per_page;
		$config['uri_segment'] = 4;
		$config['use_page_numbers'] = TRUE;
		$config['full_tag_open'] = '<ul class="pagination">';
		$config['full_tag_close'] = '</ul>';
		// first link
		$config['first_link'] = '&laquo;';
		$config['first_tag_open'] = '<li>';
		$config['first_tag_close'] = '</li>';
		// next link
		$config['next_tag_open'] = '<li>';
		$config['next_tag_close'] = '</li>';	
		// previous link
		$config['prev_tag_open'] = '<li>';
		$config['prev_tag_close'] = '</li>';
		// end link
		$config['last_link'] = '&raquo;';
		$config['last_tag_open'] = '<li>';
		$config['last_tag_close'] = '</li>';
		// current
		$config['cur_tag_open'] = '<li class="active"><a href="#">';
		$config['cur_tag_close'] = '<span class="sr-only">(current)</span></a></li>';
		// digit link
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';

		$this->pagination->initialize($config); 

		$data['paging_exportproducts'] = $this->pagination->create_links();

		////////////////////////////////////////////////////////////////////				
		
		if(!isset($data['storageProducts']) && empty($data['storageProducts']) && count($data['storageProducts']) > 0)
		{
			$data['notify'] = 'Chưa có sản phẩm nào lưu kho';
		}
		else
		{
			$tmp_storageProds = array();		
			foreach ($data['storageProducts'] as $row) 
			{
				$productObj = $this->Product_model->getEntry($row->product_id);			

				$tmp_storageProds[] = array(
						'id'			=>	$row->id,				
						'product_name'	=>	$productObj->title,
						'color'			=>	$productObj->color,
						'product'		=>	$this->Product_model->getEntry($row->product_id),
						'product_size'	=>	$this->Product_sizes_model->getEntry('code', $row->product_code),
						'storage'		=>	$this->Storage_model->getEntry($row->storage_id),
						'product_code'	=>	$row->product_code,
						'date_created'	=>	$row->created_date,
					);				
			}

			$data['storageProducts'] = $tmp_storageProds;
		}

		// if(!empty($search))
		// {
		// 	$tmp_searchData = array();
		// 	// search with code or code
		// 	foreach ($data['storageProducts'] as $key => $value) {
		// 		if(stristr($value['product_name'], $search) || stristr($value['product_code'],$search))
		// 		{
		// 			$tmp_searchData[$key] = $value;
		// 		}
		// 	}
		// }

		// if(!empty($tmp_searchData))
		// {
		// 	$data['storageProducts'] = $tmp_searchData;
		// }

		$this->session->set_userdata('currentURL', current_url());

		$this->template->load('admin/template','admin/exportw',$data);
	}

	// create new export
	public function newExportForm()
	{
		// make new export form 
		$data = array(				
				'maker'			=>	'unknown',
				'note'			=>	'unknown',
				'quantity'		=>	0,
				'active'		=>	0,
			);

		// add code to form 
		$exportFormId = $this->Export_form_model->insert($data);

		redirect('exportw/index');
	}

	// export
	public function process($id,$storage_id,$redirect = true,$export_form_id = false)
	{		
		// get export form id 
		if($export_form_id)
		{
			$exportForm = $this->Export_form_model->getEntry($export_form_id);
		}
		else
		{
			$exportForm = $this->Export_form_model->getInactiveExportForm();
		}
		
		$exportFormId = '';
		if(empty($exportForm))
		{
			// tạo phiếu xuất kho trước			
			$data = array(				
					'maker'			=>	'unknown',
					'note'			=>	'unknown',
					'quantity'		=>	0,
					'active'		=>	0,
				);

			// add code to form 
			$exportFormId = $this->Export_form_model->insert($data);
		}
		else
		{
			$exportFormId = $exportForm->id;
		}

		// get code from storage_product
		$storage_product = $this->Storage_product_model->getEntry('id', $id);		
		$product_id = $storage_product->product_id;
		$product = $this->Product_model->getEntry($product_id);
		$code = $storage_product->product_code;
		$storage_info = $this->Storage_model->getEntry($storage_product->storage_id);
		$storage_title = $storage_info->title;		
		$product_size = $this->Product_sizes_model->getEntry('code',$code);

		// create record in code_export_form
		$data = array(
				'code'					=>	$code,
				'storage'				=>	$storage_title,
				'export_form_id'		=>	$exportFormId,
				'storage_product_id'	=>	$storage_product->id,
				'active'				=>	1,
			);
		$codeport_insertId = $this->Code_export_form_model->insert($data);

		// remove code from storage_product
		$this->Storage_product_model->remove($id);	

		// remove quantity from product_sizes
		$this->Product_sizes_model->updateQuantity($code,'decrease');	

		// increase quantity of store
		$this->Storage_model->updateQuantity($storage_id,'increase');

		// log history		
		$data = array(
				'product'		=>	$product->title,
				'product_id'	=>	$product->id,
				'size'			=>	$product_size->size,
				'code'			=>	$code,
				'storage_id'	=>	$storage_info->id,
				'storage'		=>	$storage_title,
				'type'			=>	2,			
			);
		$history_id = $this->Storage_product_history_model->insertHistory($data);

		// update history id to code_export_form
		$data = array('history_id' => $history_id);

		$this->Code_export_form_model->update($data, $codeport_insertId);	

		$previous_url = $this->session->userdata('currentURL');

		if(empty($previous_url))
			$previous_url = 'exportw/index';
		// return to index
		if($redirect)
			redirect($previous_url);
	}	

	// process to print
	public function uploadExportForm($process = false,$debug_enable = false)
	{		
		$data = array();
		if($process)
		{
			if($process)
			{
				$data['export_form_id'] = $process;

				$export_form = $this->Export_form_model->getEntry($process);

				// make array to list all matched records
				$matched_export_array = array();
				// make array to list all unmatched records
				$unmatched_export_array = array();

				$code_export_form_tmp = $this->Code_export_form_tmp_model->loadAll($process);

				// add debug
				array_push($this->debug, $code_export_form_tmp);

				$data['maker_code'] = $export_form->maker_code;
				
				$i = 0;
				foreach ($code_export_form_tmp as $row) 
				{
					////////////////////// find code //////////////////////////////////////////////
					$product_code = $row->code; 			
					$cond = array('code'=>$product_code);		
					$product_matched = $this->Product_sizes_model->getProduct($cond);

					if(!empty($product_matched))
					{
						foreach ($product_matched as $row_i) 
						{
							$product = $this->Product_model->getEntry($row_i->product_id);							
							$storage_product = $this->Storage_product_model->getEntry('product_code',$product_code);

							$storage = array();
							foreach ($storage_product as $storage_i) 
							{
								$sto = $this->Storage_model->getEntry($storage_i->storage_id);
								$storage[] = array(
										'id'					=> $sto->id,
										'title'					=>  $sto->title,
										'storage_id'			=>	$storage_i->storage_id,
										'created_date'			=>	$storage_i->created_date,
										'storage_product_id'	=>	$storage_i->id,
									);
							}

							array_push($this->debug, $storage);

							$matched_export_array[]	= array(
									'size'		=> $row_i->size,
									'code'		=> $product_code,
									'product_id'=>	$product->id,
									'title'		=>	$product->title,
									'color'		=>	$product->color,
									'size'		=>	$row_i->size,
									'storage_id'=>	$storage[0]['id'],
									'storage'	=>	$storage[0]['title'],
									'storagePID'=>	$storage[0]['storage_product_id'],
								);
						}
					}
					else
					{
						$unmatched_export_array[] = $product_code;
					}					

					$i++;
				}

				array_push($this->debug, $matched_export_array);
				array_push($this->debug, $unmatched_export_array);

				/////////////////////// finish all //////////////////////
				$data['matched_export_array'] = $matched_export_array;
				$data['unmatched_export_array'] = $unmatched_export_array;

				////////////////////// session /////////////////////////////
				$this->session->set_userdata('matched_export_array', $matched_export_array);
				$this->session->set_userdata('unmatched_export_array', $unmatched_export_array);

				if($debug_enable)
				{
					echo "<pre>";
					print_r($this->debug);
					echo "</pre>";
				}

				$this->template->load('admin/template','admin/uploadExportForm',$data);
			}			
			else
			{
				$data['failed_export'] = 'Dữ liệu nhập sai ! Xin vui lòng kiểm tra lại';
				$this->template->load('admin/template','admin/uploadExportForm',$data);
			}
		}
		else
		{
			redirect('export/uploadExport.php');
		}
	}

	public function confirmExport($export_form_id = false, $debug_enable = false)
	{		
		$data['export_form_id'] = $export_form_id;

		$export_form = $this->Export_form_model->getEntry($export_form_id);

		$maker = $export_form->maker_code;

		// make array to list all matched records
		$matched_export_array = array();
		// make array to list all unmatched records
		$unmatched_export_array = array();

		$code_export_form_tmp = $this->Code_export_form_tmp_model->loadAll($export_form_id);

		// add debug
		array_push($this->debug, $code_export_form_tmp);

		$maker_code = $export_form->maker_code;
				
		$i = 0;
		foreach ($code_export_form_tmp as $row) 
		{
			////////////////////// find code //////////////////////////////////////////////
			$product_code = $row->code; 			
			$cond = array('code'=>$product_code);		
			$product_matched = $this->Product_sizes_model->getProduct($cond);

			if(!empty($product_matched))
			{
				foreach ($product_matched as $row_i) 
				{
					$product = $this->Product_model->getEntry($row_i->product_id);							
					$storage_product = $this->Storage_product_model->getEntry('product_code',$product_code);

					$storage = array();
					foreach ($storage_product as $storage_i) 
					{
						$sto = $this->Storage_model->getEntry($storage_i->storage_id);
						$storage[] = array(
									'id'					=> $sto->id,
									'title'					=>  $sto->title,
									'storage_id'			=>	$storage_i->storage_id,
									'created_date'			=>	$storage_i->created_date,
									'storage_product_id'	=>	$storage_i->id,
								);
				}

				array_push($this->debug, $storage);

				$matched_export_array[]	= array(
							'size'						=> $row_i->size,
							'code'						=> $product_code,
							'product_id'				=>	$product->id,
							'title'						=>	$product->title,
							'color'						=>	$product->color,
							'size'						=>	$row_i->size,
							'storage_id'				=>	$storage[0]['id'],
							'storage'					=>	$storage[0]['title'],
							'storagePID'				=>	$storage[0]['storage_product_id'],
							'code_export_form_tmp_id'	=>	$row->id,
						);
				}
			}
			else
			{
				$unmatched_export_array[] = $product_code;
			}					

			$i++;
		}

		///////////////////////////////// Confirm export //////////////////////////////////////////
		// get export form id 
		$exportFormId = $export_form_id;

		// get code from storage_product		
		foreach ($matched_export_array as $key => $value) 
		{
			// remve record in code_export_form_tmp 
			$this->Code_export_form_tmp_model->removeWithId($value['code_export_form_tmp_id']);

			$storage_product = $this->Storage_product_model->getEntry('id', $value['storagePID']);		

			array_push($this->debug, $storage_product);

			if(!empty($storage_product))			
			{
				$code = $storage_product->product_code;
				$product_id = $storage_product->product_id;
				$product = $this->Product_model->getEntry($product_id);
				$product_size = $this->Product_sizes_model->getEntry('code',$code);				
				$storage_info = $this->Storage_model->getEntry($storage_product->storage_id);
				$storage_title = $storage_info->title;		
				$id = $value['storagePID'];
				$storage_id = $value['storage_id'];


				// create record in code_export_form
				$data = array(
						'code'					=>	$code,
						'storage'				=>	$storage_title,
						'export_form_id'		=>	$exportFormId,
						'storage_product_id'	=>	$storage_product->id,
						'active'				=>	1,
					);
				$codeExport_insertId = $this->Code_export_form_model->insert($data);

				// remove code from storage_product
				$this->Storage_product_model->remove($id);	

				// remove quantity from product_sizes
				$this->Product_sizes_model->updateQuantity($code,'decrease');	

				// increase quantity of store
				$this->Storage_model->updateQuantity($storage_id,'increase');

				// log history		
				$data = array(
						'product'		=>	$product->title,
						'product_id'	=>	$product->id,
						'size'			=>	$product_size->size,
						'code'			=>	$code,
						'storage_id'	=>	$storage_info->id,
						'storage'		=>	$storage_info->title,
						'type'			=>	2,
					);
				$history_id = $this->Storage_product_history_model->insertHistory($data);

				// update history_id in code_export_form
				$data = array('history_id' => $history_id);

				$this->Code_export_form_model->update($data, $codeport_insertId);
			}
		}

		// update active = 1 for export form id
		$data = array('active' => 1);
		$this->Export_form_model->update($data,$exportFormId);

		if($debug_enable)
		{
			echo "<pre>";
			print_r($this->debug);
			echo "</pre>";
		}
		
		$this->session->set_userdata('notify','Phiếu xuất kho mã '.$maker.' thành công !');
		redirect('exportw/index');
	}

	public function printExport($export_form_id = false)
	{
		// make session 
		$this->session->set_userdata('confirmExportBtn','yes');

		$data['export_form_id'] = $export_form_id;

		$export_form = $this->Export_form_model->getEntry($export_form_id);

		// make array to list all matched records
		$matched_export_array = array();
		// make array to list all unmatched records
		$unmatched_export_array = array();

		$code_export_form_tmp = $this->Code_export_form_tmp_model->loadAll($export_form_id);

		// add debug
		array_push($this->debug, $code_export_form_tmp);

		$maker_code = $export_form->maker_code;
				
		$i = 0;
		foreach ($code_export_form_tmp as $row) 
		{
			////////////////////// find code //////////////////////////////////////////////
			$product_code = $row->code; 			
			$cond = array('code'=>$product_code);		
			$product_matched = $this->Product_sizes_model->getProduct($cond);

			if(!empty($product_matched))
			{
				foreach ($product_matched as $row_i) 
				{
					$product = $this->Product_model->getEntry($row_i->product_id);							
					$storage_product = $this->Storage_product_model->getEntry('product_code',$product_code);

					$storage = array();
					foreach ($storage_product as $storage_i) 
					{
						$sto = $this->Storage_model->getEntry($storage_i->storage_id);
						$storage[] = array(
									'id'					=> $sto->id,
									'title'					=>  $sto->title,
									'storage_id'			=>	$storage_i->storage_id,
									'created_date'			=>	$storage_i->created_date,
									'storage_product_id'	=>	$storage_i->id,
								);
				}

				array_push($this->debug, $storage);

				$matched_export_array[]	= array(
							'size'		=> $row_i->size,
							'code'		=> $product_code,
							'product_id'=>	$product->id,
							'title'		=>	$product->title,
							'color'		=>	$product->color,
							'size'		=>	$row_i->size,
							'storage_id'=>	$storage[0]['id'],
							'storage'	=>	$storage[0]['title'],
							'storagePID'=>	$storage[0]['storage_product_id'],
						);
				}
			}
			else
			{
				$unmatched_export_array[] = $product_code;
			}					

			$i++;
		}
		
		
		////////////////////////////////////////////////////////////////
		//load our new PHPExcel library
		$this->load->library('excel');
		//activate worksheet number 1
		$this->excel->setActiveSheetIndex(0);
		//name the worksheet
		$this->excel->getActiveSheet()->setTitle('test worksheet');
		//set cell A1 content with some text
		$this->excel->getActiveSheet()->setCellValue('A1', 'Mã KH');
		$this->excel->getActiveSheet()->setCellValue('B1', 'Mã áo');
		$this->excel->getActiveSheet()->setCellValue('C1', 'Vị trí');
		$this->excel->getActiveSheet()->setCellValue('D1', 'Tên áo');
		$this->excel->getActiveSheet()->setCellValue('E1', 'Màu áo');
		$this->excel->getActiveSheet()->setCellValue('F1', 'Size áo');

		$i = 2;

		foreach ($matched_export_array as $key => $value) 
		{
			$this->excel->getActiveSheet()->setCellValue('A'.$i, $maker_code);
			$this->excel->getActiveSheet()->setCellValue('B'.$i, $value['code']);
			$this->excel->getActiveSheet()->setCellValue('C'.$i, $value['storage']);
			$this->excel->getActiveSheet()->setCellValue('D'.$i, $value['title']);
			$this->excel->getActiveSheet()->setCellValue('E'.$i, $value['color']);
			$this->excel->getActiveSheet()->setCellValue('F'.$i, $value['size']);			

			$i++;
		}
		
		//change the font size
		//$this->excel->getActiveSheet()->getStyle('A1')->getFont()->setSize(20);
		//make the font become bold
		//$this->excel->getActiveSheet()->getStyle('A1')->getFont()->setBold(true);
		//merge cell A1 until D1
		//$this->excel->getActiveSheet()->mergeCells('A1:D1');
		//set aligment to center for that merged cell (A1 to D1)
		$this->excel->getActiveSheet()->getStyle('A1')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
				 
		$filename='phieu_xuat_kho_'.$maker_code.'.xls'; //save our workbook as this file name
		header('Content-Type: application/vnd.ms-excel'); //mime type
		header('Content-Disposition: attachment;filename="'.$filename.'"'); //tell browser what's the file name
		header('Cache-Control: max-age=0'); //no cache
				             
		//save it to Excel5 format (excel 2003 .XLS file), change this to 'Excel2007' (and adjust the filename extension, also the header mime type)
		//if you want to save it as .XLSX Excel 2007 format
		$objWriter = PHPExcel_IOFactory::createWriter($this->excel, 'Excel5');  
		//force user to download the Excel file without writing it to server's HD
		$objWriter->save('php://output');		
	}

	public function info($storage_id = false)
	{		
		// store storage_id
		$data['storage_id'] = $storage_id;

		// lay thong tin kho
		$data['storage'] = $this->Storage_model->getEntry($storage_id);

		// get all logs of importing
		$data['historyImport'] = $this->Storage_product_history_model->getEntry('storage_id',$storage_id);		
	}

	public function confirm()
	{
		// load inactive export then ask to finish first
		$exportForm = $this->Export_form_model->getInactiveExportForm();

		if(!empty($exportForm))
		{
			// deactive button create new export
			$data['inactiveMakeExport'] = 'yes';

			// list all code will output
			$data['exportCodes'] = $this->Code_export_form_model->loadAll($exportForm->id);

			$tmp_array = array();

			// echo "<pre>";
			// print_r($data['exportCodes']);
			// echo "</pre>";

			foreach($data['exportCodes'] as $code)
			{
				$product_size = $this->Product_sizes_model->getEntry('code', $code->code);
				$product = $this->Product_model->getEntry($product_size->product_id);				
				$tmp_array[] = array(
						'product'				=>	$product->title,
						'color'					=>	$product->color,
						'product_size'			=>	$product_size->size,
						'product_code'			=>	$product_size->code,
						'history_id'			=>	$code->history_id,
						'code'					=> $code->code,
						'export_form_id'		=>	$code->export_form_id,
						'storage'				=> $code->storage,
						'date_created'			=>	$code->date_created,
					);
			}

			$data['exportCodes'] = $tmp_array;

			// echo "<pre>";
			// print_r($data['exportCodes']);
			// echo "</pre>";

			//die();

			$this->template->load('admin/template','admin/exportForm',$data);
		}		
		else
		{
			redirect('exportw/index');
		}	
	}

	public function success()
	{
		// load inactive export then ask to finish first
		$exportForm = $this->Export_form_model->getInactiveExportForm();

		if(!empty($exportForm))
		{
			// deactive button create new export
			$data['inactiveMakeExport'] = 'yes';

			// list all code will output
			$data['exportCodes'] = $this->Code_export_form_model->loadAll($exportForm->id);

			// make new export form 
			$export = array(				
				'maker'			=>	$this->input->post('maker'),
				'note'			=>	$this->input->post('note'),
				'quantity'		=>	0,
				'active'		=>	1,
			);					

			// load history id and do update maker, note
			foreach($data['exportCodes'] as $code)
			{
				$history_id = $code->history_id;

				$history_data = array(
						'people'	=>	$this->input->post('maker'),
						'reason'	=>	$this->input->post('note'),
					);
				
				$this->Storage_product_history_model->updateHistory($history_data, $history_id);
			}

			$this->Export_form_model->update($export,$exportForm->id);

			$this->template->load('admin/template','admin/successExport',$data);
		}		
	}

	// history
	public function history($start = false)
	{		
		$fromDate = $this->input->get('fromDate',true);
		$toDate = $this->input->get('toDate',true);		

		$warning = $this->session->userdata('warning');

		if(!empty($warning))
		{
			$data['warning'] = $warning;
			$this->session->unset_userdata('warning');
		}

		// if not empty $fromDate, $toDate
		if(!empty($fromDate))		
		{
			$data['fromDate'] = $fromDate;
			$fromDate = date('Y-m-d', strtotime($fromDate));
			$this->session->set_userdata('fromDate',$fromDate);
		}		
		// $toDate
		if(!empty($toDate))
		{
			$data['toDate'] = $toDate;
			$toDate = date('Y-m-d', strtotime($toDate));
			$this->session->set_userdata('toDate',$toDate);
		}		

		///////// session $fromDate $toDate /////////////
		$session_fromDate = $this->session->userdata('fromDate');
		$session_toDate = $this->session->userdata('toDate');
		/////////////////////////////////////////////////

		if(!empty($session_fromDate))
		{
			$data['fromDate'] = $session_fromDate;
		}
		if(!empty($session_toDate))
		{
			$data['toDate'] = $session_toDate;
		}
		
		$cond = array();
		// prepare condition
		if(!empty($data['fromDate']))
			$cond['from_date'] = $data['fromDate'];
		if(!empty($data['toDate']))
			$cond['to_date'] = $data['toDate'];

		if(empty($start))
			$start = 1;

		$start = ($start - 1) * $this->per_page;
		$limit = $this->per_page;

		// history: type=1 import type=2 export
		$return = $this->Storage_product_history_model->loadHistoryV3(2,$cond,$limit,$start);
		$data['history'] = $return['data'];
		$total_history = $return['count'];
		$data['total'] = $total_history;

		////////////////// pagination //////////////////////////////////////
		$this->load->library('pagination');

		$config['base_url'] = site_url('exportw/history/');
		$config['total_rows'] = $total_history;
		$config['per_page'] = $this->per_page;
		$config['uri_segment'] = 3;
		$config['use_page_numbers'] = TRUE;
		$config['full_tag_open'] = '<ul class="pagination">';
		$config['full_tag_close'] = '</ul>';
		// first link
		$config['first_link'] = '&laquo;';
		$config['first_tag_open'] = '<li>';
		$config['first_tag_close'] = '</li>';
		// next link
		$config['next_tag_open'] = '<li>';
		$config['next_tag_close'] = '</li>';	
		// previous link
		$config['prev_tag_open'] = '<li>';
		$config['prev_tag_close'] = '</li>';
		// end link
		$config['last_link'] = '&raquo;';
		$config['last_tag_open'] = '<li>';
		$config['last_tag_close'] = '</li>';
		// current
		$config['cur_tag_open'] = '<li class="active"><a href="#">';
		$config['cur_tag_close'] = '<span class="sr-only">(current)</span></a></li>';
		// digit link
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';

		$this->pagination->initialize($config); 

		$data['paging_history'] = $this->pagination->create_links();

		////////////////////////////////////////////////////////////////////

		$this->template->load('admin/template','admin/exportw_history',$data);
	}

	// print excel
	function printExcel()
	{
		$fromDate = $this->input->get('fromDate',true);
		$toDate = $this->input->get('toDate',true);

		$cond = array();
		if(!empty($fromDate))
		{
			$data['fromDate'] = $fromDate;
			$cond['from_date'] = date('Y-m-d', strtotime($fromDate));
		}
		if(!empty($toDate))
		{
			$data['toDate'] = $toDate;
			$cond['to_date'] = date('Y-m-d', strtotime($toDate));	
		}

		// history: type=1 import type=2 export
		$data['history'] = $this->Storage_product_history_model->loadHistoryForPrintExcel(2,$cond);				

		if(empty($data['history']))		
		{
			$this->session->set_userdata('warning','Dữ liệu trống');
			redirect('exportw/history');
		}

		////////////////////////////////////////////////////////////////
		//load our new PHPExcel library
		$this->load->library('excel');
		//activate worksheet number 1
		$this->excel->setActiveSheetIndex(0);
		//name the worksheet
		$this->excel->getActiveSheet()->setTitle('in xuat kho');
		//set cell A1 content with some text
		$this->excel->getActiveSheet()->setCellValue('A1', 'STT');
		$this->excel->getActiveSheet()->setCellValue('B1', 'Người xuất');
		$this->excel->getActiveSheet()->setCellValue('C1', 'Lý do');
		$this->excel->getActiveSheet()->setCellValue('D1', 'Sản phẩm');
		$this->excel->getActiveSheet()->setCellValue('E1', 'Size áo');
		$this->excel->getActiveSheet()->setCellValue('F1', 'Mã áo');
		$this->excel->getActiveSheet()->setCellValue('G1', 'Kho');
		$this->excel->getActiveSheet()->setCellValue('H1', 'Ngày tạo');		

		$i = 2;
		$j = 1;
		$today = date('YmdHis',strtotime('now'));

		foreach ($data['history'] as $row) 
		{
			$this->excel->getActiveSheet()->setCellValue('A'.$i, $j);
			$this->excel->getActiveSheet()->setCellValue('B'.$i, $row->people);
			$this->excel->getActiveSheet()->setCellValue('C'.$i, $row->reason);
			$this->excel->getActiveSheet()->setCellValue('D'.$i, $row->product);
			$this->excel->getActiveSheet()->setCellValue('E'.$i, $row->size);
			$this->excel->getActiveSheet()->setCellValue('F'.$i, $row->code);			
			$this->excel->getActiveSheet()->setCellValue('G'.$i, $row->storage);			
			$this->excel->getActiveSheet()->setCellValue('H'.$i, $row->date_created);			

			$j++;
			$i++;
		}
		
		//change the font size
		//$this->excel->getActiveSheet()->getStyle('A1')->getFont()->setSize(20);
		//make the font become bold
		$this->excel->getActiveSheet()->getStyle('A1')->getFont()->setBold(true);
		$this->excel->getActiveSheet()->getStyle('B1')->getFont()->setBold(true);
		$this->excel->getActiveSheet()->getStyle('C1')->getFont()->setBold(true);
		$this->excel->getActiveSheet()->getStyle('D1')->getFont()->setBold(true);
		$this->excel->getActiveSheet()->getStyle('E1')->getFont()->setBold(true);
		$this->excel->getActiveSheet()->getStyle('F1')->getFont()->setBold(true);
		$this->excel->getActiveSheet()->getStyle('G1')->getFont()->setBold(true);
		$this->excel->getActiveSheet()->getStyle('H1')->getFont()->setBold(true);
		//merge cell A1 until D1
		//$this->excel->getActiveSheet()->mergeCells('A1:D1');
		//set aligment to center for that merged cell (A1 to D1)
		$this->excel->getActiveSheet()->getStyle('A1')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
				 
		$filename='xuat_kho_'.$today.'.xls'; //save our workbook as this file name
		header('Content-Type: application/vnd.ms-excel'); //mime type
		header('Content-Disposition: attachment;filename="'.$filename.'"'); //tell browser what's the file name
		header('Cache-Control: max-age=0'); //no cache
				             
		//save it to Excel5 format (excel 2003 .XLS file), change this to 'Excel2007' (and adjust the filename extension, also the header mime type)
		//if you want to save it as .XLSX Excel 2007 format
		$objWriter = PHPExcel_IOFactory::createWriter($this->excel, 'Excel5');  
		//force user to download the Excel file without writing it to server's HD
		$objWriter->save('php://output');	
	}

	//////////// add warning to code /////////////////////////////////////
	// public function showWarning($level, $text)
	// {
	// 	switch ($level) {
	// 		case 'value':
	// 			# code...
	// 			break;
			
	// 		default:
	// 			# code...
	// 			break;
	// 	}
	// }

}
